package algorithm.offer;

/**
 * > n & (n-1)
 * > 例如
 *          n   =7    =  (0111)
 * 	    	n-1 =6    =  (0110)
 * 	    	n & (n-1) =  (0110)
 * 	    	--------------------
 * 	        =	7右移一位后的结果
 * 	        右移运算 >> 正数左边补0  负数左边补1 右边舍弃
 * 	                    每右移一位 = 数字/2
 */
public class Offer_15_hammingWeight {
    // you need to treat n as an unsigned value
    public static int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        int res = hammingWeight(9);
        System.out.println(res);
    }
}
